<template>
  <div class="Register">
    <el-row>
      <el-col :span="24">
        <el-card class="ms-register">
          <div class="ms-title">注册</div>
          <el-form :model="form" :rules="rules" ref="register" label-width="120px" style="padding: 10px 20px">
            <el-row>
              <el-col :span="10">
                <el-form-item label="联系人：" prop="full_name">
                  <el-input v-model="form.full_name"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="联系方式：" prop="phone">
                  <el-input v-model="form.phone"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="14">
                <el-form-item label="验证码：" prop="phone_access">
                  <el-input v-model="form.phone_access">
                    <el-button slot="append" type="primary" v-if="showtime === null" @click="sendRegisterCode()">获取验证码
                    </el-button>
                    <el-button slot="append" type="primary" v-else :loading="loading">
                      请稍等({{showtime}})
                    </el-button>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="10">
                <el-form-item label="密码：" prop="password">
                  <el-input show-password v-model="form.password"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="确认密码：" prop="check_password">
                  <el-input show-password v-model="form.check_password"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="详细地址：">
              <el-input v-model="form.field_04"></el-input>
            </el-form-item>
            <div class="login-btn">
              <el-button type="primary" plain @click="toLogin">返回登录</el-button>
              <el-button type="primary" @click="submitForm">注册申请</el-button>
            </div>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import {mapState} from 'vuex';

  export default {
    name: "Register",
    computed: {
      ...mapState(['token'])
    },
    props: [],
    data() {
      var validatePwd = (rule, value, callback) => {
        if (this.form.password === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.form.check_password !== '') {
            this.$refs.register.validateField('check_password');
          }
          callback();
        }
      };
      var validateCheckPwd = (rule, value, callback) => {
        if (this.form.check_password === '') {
          callback(new Error('请再次输入密码'));
        } else if (this.form.check_password !== this.form.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        // 计时器,注意需要进行销毁
        timeCounter: null,
        // null 则显示按钮 秒数则显示读秒
        showtime: null,
        loading: false,
        category: [],
        form: {
          full_name: "",
          password: "",
          check_password: "",
          phone: "",
          phone_access: "",
          field_04: '',       //详细地址
        },
        rules: {
          full_name: [{required: true, message: '请输入真实姓名'}],
          password: [
            {validator: validatePwd, required: true, trigger: 'blur'},
            {min: 8, max: 16, message: '长度在 8 到 16 个字符', trigger: 'blur'}
          ],
          check_password: [{validator: validateCheckPwd, required: true, trigger: 'blur'}],
          phone: [{required: true, validator: this.checkPhone, trigger: 'blur'}],
          phone_access: [{required: true, message: '请输入验证码'}],
        },
      }
    },
    methods: {
      //发送验证码后的倒计时
      // 倒计时显示处理
      countDownText(s) {
        this.showtime = `${s}`
      },
      // 倒计时 60秒 不需要很精准
      countDown(times) {
        const self = this;
        // 时间间隔 1秒
        const interval = 1000;
        let count = 0;
        self.timeCounter = setTimeout(countDownStart, interval);

        function countDownStart() {
          if (self.timeCounter == null) {
            return false;
          }
          count++;
          self.countDownText(times - count + 1);
          if (count > times) {
            clearTimeout(self.timeCounter);
            self.showtime = null;
            this.loading = false;
          } else {
            self.timeCounter = setTimeout(countDownStart, interval)
          }
        }
      },

      //发送验证码的方法，传入参数为form表单的ref，发送验证码之前需校验一次手机号
      sendRegisterCode() {
        this.form.phone_access = "";
        this.$refs.register.validateField('phone', valid => {
          if (!valid) {
            this.$http.post('/phoneauth/', {phone: this.form.phone}).then(() => {
              this.countDown(60);
              this.$message({
                message: "成功",
                type: "success"
              });
            }).catch(e => {
              this.$message.error({
                message: e.response.statusText
              });
            });
          } else {
            this.$message.error(valid)
          }
        });
      },

      //提交注册申请的方法
      submitForm() {
        this.$refs.register.validate(valid => {
          if (valid) {
            this.$http.post('/userrequirecreate/', ).then(resp => {
              this.$router.push({name: 'registerSuccess'});
              this.$message({
                message: '提交成功！',
                type: 'success',
                duration: 2000,
                center: true
              });
            }).catch(e => {
              if (e.response.data && e.response.data.phone) {
                this.$message.error("此账号已存在")
              } else if (e.response.data && e.response.data.non_field_errors) {
                this.$message.error(e.response.data.non_field_errors[0])
              }
            })
          }
        })
      },
      toLogin() {
        this.$emit('toLogin');
      },
      checkPhone(rule, value, callback) {
        if (!value) {
          return callback(new Error('请输入手机号'))
        } else {
          const reg = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/
          if (reg.test(value)) {
            callback()
          } else {
            return callback(new Error('请输入正确的手机号'))
          }
        }
      },
    },
    mounted() {
    }
  }
</script>

<style>
  .ms-title {
    /*position: relative;*/
    width: 100%;
    line-height: 50px;
    text-align: center;
    font-size: 20px;
    color: #333;
    border-bottom: 1px solid #ddd;
  }

  .ms-register {
    width: 800px;
    margin: 50px auto;
    border-radius: 5px;
    background: rgba(255, 255, 255, 1.0);
    /*overflow: hidden;*/
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 120px;
    height: 120px;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }

  .avatar {
    width: 120px;
    height: 120px;
    display: block;
  }

  .login-btn {
    text-align: center;
  }

  .login-btn button {
    width: 25%;
    height: 36px;
    margin-bottom: 10px;
  }
</style>
